/*
* @Author: jiameng15
* @Date: 2020-03-04 22:47:07
* @Last Modified by: jiameng15
* @Last Modified time: 2020-04-14 20:32:48
*/
<template>
  <div>
    <div class="row-header">
      <el-form ref="searchForm" :model="searchForm" label-width="50px" :inline="true">
        <el-form-item label=" " prop="loginName">
          <el-autocomplete class="inline-input" size="small" v-model="searchForm.loginName" style="width: 300px;"
                           :fetch-suggestions="querySearch" :trigger-on-focus="false"
                           @select="handleSelectLoginName" placeholder="请输入代理账号" clearable>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label=" " prop="loginName">
          <el-select v-model="searchForm.type" placeholder="请选择时间范围">
            <el-option value="" label="请选择时间范围"></el-option>
            <el-option value="DAY" label="日"></el-option>
            <el-option value="MONTH" label="月"></el-option>
            <el-option value="YEAR" label="年"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" " prop="loginName">
          <transition name="el-fade-in-linear" class="message-residue">
            <div v-show="blink" :style="{'color':residue<2000?'#e6a23c':'#67c23a'}">短信剩余量：{{ residue }}</div>
          </transition>
        </el-form-item>
      </el-form>
      <div class="row-form-btn">
        <el-button size="mini" type="shenda" icon="el-icon-bank-card" @click="buyMessage()">充值</el-button>
        <el-button type="shenda" size="mini" icon="el-icon-search" @click="beforeinitData">查询</el-button>
        <el-button size="mini" type="shenda" icon="el-icon-refresh-right" @click="resetForm('searchForm')">重置</el-button>
      </div>
    </div>
    <div class="sd-page-line"></div>
    <div class="row-main">
      <el-button type="shenda" size="mini" @click="initData"><i class="el-icon-refresh"></i> 刷新数据</el-button>
      <el-button size="mini" @click="changeSearchFormType('ALL')"
                 :class="searchForm.type==='ALL'?'ALL':'is-plain'">全部
      </el-button>
      <el-button size="mini" @click="changeSearchFormType('LASTMONTH')"
                 :class="searchForm.type==='LASTMONTH'?'':'is-plain'">上月
      </el-button>
      <el-button size="mini" @click="changeSearchFormType('MONTH')"
                 :class="searchForm.type==='MONTH'?'':'is-plain'">当月
      </el-button>
      <el-button size="mini" @click="changeSearchFormType('DAY')"
                 :class="searchForm.type==='DAY'?'':'is-plain'">今日
      </el-button>
      <el-table :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }" :data="tableData" tooltip-effect="dark" class="row-main-table"
                v-loading.fullscreen="mainTableLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)" ref="table">
        <el-table-column type="index" label="序号" align="center" width="100"></el-table-column>
        <el-table-column prop="loginName" label="代理账号" align="center"></el-table-column>
        <el-table-column prop="messageNum" label="发送数量" align="center"></el-table-column>
<!--        <el-table-column label="操作" width="200" align="center">
          <template v-slot="{ row, rowIndex }">
            <el-button type="primary" size="mini" @click="detailsList(row)" :loading="buttonRetryLoading">查看详情</el-button>
          </template>
        </el-table-column>-->
      </el-table>
      <div :style="{'overflow':$store.state.app.screenWidth<992?'scroll':'auto'}">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="row-main-pager"
          :current-page.sync="page.current"
          :page-size="page.size"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          background></el-pagination>
      </div>

    </div>
    <el-dialog class="delete" top="33vh" :visible.sync="deleteVisible" :append-to-body="true" width="500px" title="充值短信">
      <!-- <span style="display: flex; justify-content: center;">充值短信</span> -->
      <el-form ref="saveInfo" :model="saveInfo" :rules="formRules" v-if="!showResult" label-width="120px">
        <el-form-item label="套餐名称:" prop="id">
          <el-select
            placeholder="请选择充值数量"
            style="width: 100%;"
            v-model="saveInfo.id"
            @change="goodsChange"
          >
            <el-option v-for="item in goodsOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="erCode!==''" label="售价">
          <span v-if="erCode!==''">{{ salePrice }}元</span>
        </el-form-item>
        <el-form-item v-if="erCode!==''" label="收款码">
          <img :src="erCode" alt="" v-if="erCode!==''"/>
        </el-form-item>
        <!--        <div><span v-if="erCode!==''">售价：{{ salePrice }}</span><img :src="erCode" alt="" v-if="erCode!==''" /></div>-->
      </el-form>
      <span v-if="showResult">{{ payResult }}</span>
      <span class="dialog-footer" slot="footer" >
        <el-button @click="closeDialog" size="small">取 消</el-button>
        <el-button type="primary" @click="buyConfirm('saveInfo')" size="small" v-preventReClick v-if="erCode===''">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getShortMessageList,      // 获取短信列表
  getUsableCount,           // oem查询可用短信数量的接口
  getLoginName,             // 模糊查询(暂定)
  getMessageGoodsOptions,   // 充值短信,可选列表
  getPayCodeImg,            // 付款二维码
  getOemOrderById,          // 支付结果轮询
} from '@/api/getData'

export default {
  name: 'ShortMessage',
  data() {
    return {
      payResult: '',
      erCode: '',
      optionsLoading: true,
      saveInfo: {
        id: '',
      },
      goodsOptions: [],
      timer: null,
      blink: true,
      residue: '--',
      loginNames: [],// 模糊查询结果数组
      deleteVisible: false, // 删除显隐
      // 查询条件
      searchForm: {
        loginName: '',  // 代理名字
        type: '',       // 时间类型  本日DAY  本月 MONTH  上月LASTMONTH
      },
      mainTableLoading: false,
      buttonRetryLoading: false,
      salePrice: '',
      // 分页
      page: {
        current: 1,
        size: 10,
      },
      tablePage: {
        pageSize: 15,
        pageSizes: [5, 15, 20, 50, 100, 200, 500, 1000]
      },
      tableData: [],
      value: false,
      id: '',
      formRules: {
        id: [
          {required: true, message: '请选择充值数量', trigger: 'change'}
        ],
      },
      pagekey: '',
      showResult: false,
      paymentList: [],
      color: ''
    }
  },
  components: {},
  watch: {
    'user': function (val, oldval) {
      this.form.belongId = val.value
      this.form.username = val.label
    },
    showResult: false,

  },
  created() {
    let t = localStorage.getItem('theme');
    this.color = t ? JSON.parse(t).lightBg : '#409EFF';
    let searchObj = sessionStorage.getItem(this.$route.path)
    if (searchObj != undefined && searchObj != null && searchObj != '') {
      this.searchForm = JSON.parse(searchObj)
      this.page = this.searchForm.page
    }
    this.usableCount()
    this.initData()
    this.getgoodsOptions()
    window.clearInterval(this.timer);
  },
  methods: {
    async buyMessage() {
      this.deleteVisible = true;
      this.erCode = '';
      this.pagekey = await this.$getPageKey();
      // this.$alert('如短信剩余量不足请尽快去充值平台进行充值！', '', {
      //   confirmButtonText: '确定',
      //   callback: action => {
      //
      //   }
      // });
    },
    async getgoodsOptions() {
      this.goodsOptions = []
      const returnData = await getMessageGoodsOptions({
        dictGoodsType: 'SHORT_MESSAGE'
      })
      if (returnData._result) {
        returnData.data.map(item => {
          let data = {}
          data.id = item.id
          data.name = item.goodsName
          this.goodsOptions.push(data)
        })
        this.saveInfo.id = this.goodsOptions[0].id
        this.optionsLoading = false
      } else {
        this.optionsLoading = false
      }
    },
    handleSelectLoginName(item) {
      this.beforeinitData()
    },

    changeSearchFormType(type) {
      this.searchForm.type = type
      this.initData()
    },

    detailsList(row) {
      this.$router.push({
        path: '/ShortMessage/details',
        query: {
          type: this.searchForm.type,
          firstUserId: row.firstUserId,
        }
      })
    },

    // 充值确认
    buyConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        // if (!valid) { //测试
        if (valid) {
          this.payImg()
        } else {
          return false;
        }
      })
    },
    async payImg() {
      const returnData = await getPayCodeImg({
        goodsId: this.saveInfo.id,
      }, {
        pagekey: this.pagekey
      })
      if (returnData._result) {
        this.erCode = returnData.data.imgBase64
        this.salePrice = returnData.data.goods.price
        this.timer = setInterval(async () => {
          let order = await getOemOrderById({id: returnData.data.id})
          if (order.data&&order.data.dictOrderStatus == 'USER_ORDER_HAVE_PAY') {
            clearInterval(this.timer);
            this.$message.success("支付成功")
            this.deleteVisible = false
          }
        }, 2000)
        this.pagekey = await this.$getPageKey();
      }
    },
    //关闭支付弹窗
    closeDialog(){
      this.deleteVisible = false;
      window.clearInterval(this.timer)
    },
    handleCurrentChange(currentPage) {
      this.page.current = currentPage;
      this.initData();
    },
    handleSizeChange(pageSize) {
      this.page.current = 1;
      this.page.size = pageSize;
      this.initData()
    },
    beforeinitData() {
      this.page.current = 1
      this.initData()
    },
    async initData(theKey) {
      // this.mainTableLoading = true;
      this.searchForm.page = this.page;
      sessionStorage.setItem(this.$route.path, JSON.stringify(this.searchForm))
      const returnData = await getShortMessageList(this.searchForm, {
        obj: this,
        key: 'tableLoading;' + theKey
      })

      this.tableData = []
      if (returnData._result) {
        // 数据回显
        returnData.data.records.map(item => {
          const data = {}
          data.loginName = item.loginName
          data.messageNum = item.messageNum
          data.firstUserId = item.firstUserId === null ? '' : item.firstUserId
          this.tableData.push(data)
        })
        // this.tableLoading = false
        this.page.total = returnData.data.total
      }
      this.mainTableLoading = false;
    },
    // 重置搜索并初始化数据
    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.searchForm = {
        loginName: '', // 代理账号
        type: '' // 日期类型
      }
      this.initData()
    },
    // 账户名称模糊查询接口
    async querySearch(queryString, cb) {
      let a = await getLoginName({
        loginname: this.searchForm.loginName
      });
      if (a._result) {
        this.loginNames = [];
        for (let i = 0; i < a.data.length; i++) {
          this.loginNames.push({value: a.data[i]});
        }
      }
      var loginNames = this.loginNames;
      //var results = queryString ? loginNames.filter(this.createFilter(queryString)) : loginNames;
      // 调用 callback 返回建议列表的数据
      cb(loginNames);
    },
    async usableCount() {
      let returnData = await getUsableCount({})
      if (returnData._result) {
        this.residue = returnData.data
        if (this.residue < 2000) {
          this.timer = setInterval(() => {
            this.blink = !this.blink
          }, 500);
        } else {
          clearInterval(this.timer);
        }
      }
    },
    goodsChange() {

    }
  },
  beforeDestroy() {
    window.clearInterval(this.timer)
  }
}
</script>
<style scoped lang="scss">

.drawer_form {
  padding: 50px;
  overflow-y: auto;
}

.notice_drawer_form {
  width: 100%;
}

.recentAdd li {
  list-style: none;
  float: left;
  margin-right: 5px;
  line-height: 15px;
}

.message-residue {
  width: 200px;
  display: inline-block;
}

.residue-wapper {
  // width: 100%;
  // width: 300px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  .residue-box {
    width: calc(100% - 83px);
    height: 29px
  }
}
</style>
